# !/usr/bin/env python3
# -*- coding: utf-8 -*-

from nonebot.typing import T_State
from nonebot.matcher import Matcher
from nonebot.adapters import Bot, Event
from nonebot.permission import SUPERUSER
from nonebot import get_driver, on_command, on_notice, on_message
from nonebot.adapters.cqhttp import PrivateMessageEvent, PokeNotifyEvent
from nonebot.adapters.cqhttp.message import Message

from .config import Config
from .data_source import *

global_config = get_driver().config
adminID = global_config.dict()["admin_id"]

status_config = Config(**global_config.dict())

command = on_command("状态", permission=SUPERUSER, priority=10)


@command.handle()
async def server_status(bot: Bot, matcher: Matcher):
    data = []
    if status_config.server_status_os:
        status = os_status()
        data.append("#OS: " + status)

    if status_config.server_status_cpu:
        if status_config.server_status_per_cpu:
            data.append("#CPU:")
            for index, per_cpu in enumerate(per_cpu_status()):
                data.append(f"  *core{index + 1}: {float(per_cpu):02d}%")
        else:
            data.append(f"#CPU: {float(cpu_status()):02.2f}%")

    if status_config.server_status_memory:
        data.append(
            f"#RAM: {float(memory_absolute()[0]):.1f}G/{float(memory_absolute()[1]):.1f}G = {float(memory_percent()):02.2f}% ")

    if status_config.server_status_disk:
        data.append(
            f"#Disk: {int(disk_usage()[0])}G/{int(disk_usage()[1])}G = {(disk_usage()[0] / disk_usage()[1]) * 100:02.2f}% ")

        # for k, v in disk_usage_detail().items():
        #    data.append(f"  {k}: {int(v.percent):02d}%")
    if status_config.server_status_device:
        data.append(device_info())

    await matcher.send(message="\n".join(data))


# 响应QQ群戳一戳
async def _group_poke(bot: Bot, event: Event, state: T_State) -> bool:
    return isinstance(event, PokeNotifyEvent) and str(
        event.user_id) in global_config.superusers and event.is_tome()


# 响应戳一戳
async def _poke(bot: Bot, event: Event, state: T_State) -> bool:
    return (isinstance(event, PrivateMessageEvent) and
            event.sub_type == "friend" and event.message[0].type == "poke")


group_poke = on_notice(_group_poke, priority=10, block=True)
group_poke.handle()(server_status)

poke = on_message(_poke, permission=SUPERUSER, priority=10)
poke.handle()(server_status)

driver = get_driver()


# 这里配置一个开机自启动发送信息的函数
@driver.on_bot_connect
async def debug_test(bot: Bot):
    await status_start(bot)
    pass


async def status_start(bot: Bot):
    get_adminID()
    await bot.call_api("send_private_msg",
                       user_id=adminID,
                       message=Message("小美起床开始工作啦😊"),
                       auto_escape=False)  # 可直接调用go-cqhttp的API函数
    pass
